<!--楼层管理-->
<template>
  <!-- 搜索卡片 -->
  <el-card shadow="hover" style="margin: 20px;">
    <el-form :inline="true">
      <el-row :gutter="10" style="height: 40px;">
        <!-- 现有的表单项 -->
        <el-col :span="6">
          <el-form-item label="房间编号" style="width: 90%;">
            <el-input placeholder="请输入房间编号"
                      v-model="searchRoomForm.roomNumber "/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房间类型" style="width: 90%;">
            <el-input placeholder="请输入房间类型"
                      v-model="searchRoomForm.type"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房间容量" style="width: 90%;">
            <el-input placeholder="请输入房间容量"
                      v-model="searchRoomForm.capacity"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="margin-left: 30px;">
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="loadRoom">查询</el-button>
            <el-button link
                       @click="toggleCollapse">
              {{ isCollapsed ? '收起' : '展开' }}
              <el-icon :size="16" :class="{ 'rotate-icon': isCollapsed }">
                <CaretRight/>
              </el-icon>
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 折叠 -->
      <transition name="fade">
        <div v-if="isCollapsed" style="margin-top: 10px;">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="房间状态" style="width: 90%;">
                <el-select placeholder="请选择" v-model="searchRoomForm.status">
                  <el-option label="占用" value="1"/>
                  <el-option label="空闲" value="2"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </transition>
    </el-form>
  </el-card>

  <el-card style="margin: 20px;">
    <el-button type="success" @click="addRoom">添加房间</el-button>
    <el-button type="primary" @click="exportEmployees">导出房间信息</el-button>
    <el-table :data="roomArr" stripe style="margin-top: 20px;">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column label="房间编号" prop="roomNumber" align="center"/>
      <el-table-column label="房间类型" prop="type" align="center" :formatter="roomTypeFormatter"/>
      <el-table-column label="房间容量" prop="capacity" align="center"/>
      <el-table-column label="房间状态" prop="status" align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="updateStatus(scope.row.id, scope.row.status)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="editRoom(scope.row.id)">编辑</el-button>
          <el-button link type="primary" @click="deleteRoom(scope.row.id)"> 删除</el-button>
          <el-button link type="primary" @click="findAll(scope.row.id)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <el-dialog :title="roomTitle"
             v-model="roomVisible"
             style=" position: absolute;
                       top: 30%;
                       left: 40%;
                       transform: translate(-30%, -40%);
                       width: 1000px;
                       padding: 40px;"
             :before-close="handleClose"
  >
    <el-form ref="form" label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="房间编号">
            <el-input type="text"  placeholder="请输入房间编号"
                      v-model="saveRoomForm.roomNumber"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间类型">
            <el-select placeholder="请选择房间类型" v-model="saveRoomForm.type">
              <el-option v-for="item in roomTypeArr"
                         :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="房间容量">
            <el-input type="text" placeholder="请输入房间容量" v-model="saveRoomForm.capacity"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间状态状态">
            <el-radio-group v-model="saveRoomForm.status">
              <el-radio label="占用" value="1" border style="margin: 0;"/>
              <el-radio label="空闲" value="0" border/>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveRoom">保存</el-button>
    </template>
  </el-dialog>


<!--  详情信息-->
  <el-dialog v-model="particularsVisible" style="width: 800px;
                                                 position: absolute;
                                                 top: 35%;left: 40%;
                                                 transform: translate(-20%, -50%);
                                                 padding: 20px">
    <el-descriptions title="详情信息"
                     border
                     label-width="80px"
                     column="2">
      <el-descriptions-item label="房间编号" align="center">{{ particularsData.roomNumber }}</el-descriptions-item>
      <el-descriptions-item label="房间类型" align="center">
        {{ roomTypeFormatter(particularsData,null,particularsData.type) }}
      </el-descriptions-item>
      <el-descriptions-item label="房间容量" align="center">{{ particularsData.capacity }}</el-descriptions-item>
      <el-descriptions-item label="房间状态" align="center" >
        <template #default="scope">
          <span v-if="particularsData.status  == 1">占用</span>
          <span v-else-if="particularsData.status  == 0">空闲</span>
        </template>
      </el-descriptions-item>


    </el-descriptions>
    <component :is="RoomHaveView"></component>

  </el-dialog>

</template>

<script setup>
import {onMounted, ref} from 'vue';
import {CaretRight} from "@element-plus/icons-vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
import * as XLSX from "xlsx";
import router from "@/router";
import RoomHaveView from  "@/views/assets/RoomHavaView.vue";

const isCollapsed = ref(false);

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

const roomVisible = ref(false);
const roomTitle = ref('添加房间');
const handleClose = () => {
  roomVisible.value = false;
};
const addRoom = () => {
  roomVisible.value = true;
  roomTitle.value = '添加房间';
};
//定义对象用来保存收集房间表单数据
const saveRoomForm = ref({
  roomNumber: '',
  type: '',
  capacity: '',
  status: '',

});
// 定义对象用来保存房间搜索条件
const searchRoomForm = ref({ roomNumber: '', capacity: '', type: '',status: '' });

//定义数组保存房间列表表格数据
const roomArr = ref([]);

//定义保存房间的方法
const saveRoom = ()=>{
  console.log(saveRoomForm.value);
  let data = qs.stringify(saveRoomForm.value)
  console.log(data)
  axios.post(BASE_URL+'/v1/room/save',data).then((response)=>{
    if (response.data.code === 2000){
      ElMessage.success('保存成功!')
      saveRoomForm.value={};
      roomVisible.value=false;
      loadRoom();
    }else {
      ElMessage.error(response.data.msg)
    }
  })
}
//导出数据
const exportEmployees = async () => {
  loadRoom();
  try {
    // 定义固定的表头
    const headers = [
      'id', 'roomNumber', 'type', 'capacity','status',
      'createTime', 'updateTime'
    ];

    // 将 JSON 数据转换为二维数组
    const data = roomArr.value.map(employee => headers.map(header => employee[header]));

    // 检查数据有效性
    if (!data.length || !data.every(row => Array.isArray(row) && row.length === headers.length)) {
      errorInfo('导出失败：数据为空');
      return;
    }

    // 直接在数据前插入表头
    data.unshift(headers);

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // 动态生成文件名
    // 获取当前日期并格式化为 YYYY_MM_DD 格式
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
    const day = String(now.getDate()).padStart(2, '0');

    const formattedDate = `${year}_${month}_${day}`;
    const fileName = `employees_export_${formattedDate}.xlsx`;

    // 导出Excel文件
    XLSX.writeFile(wb, fileName);

    // 提示用户导出成功
    OKInfo('导出成功');
  } catch (error) {
    errorInfo('导出失败，请检查控制台日志');
  }
};


//定义加载用户列表的方法
const loadRoom = () =>{
  console.log(saveRoomForm.value)
  let data = qs.stringify(searchRoomForm.value);
  axios.get(BASE_URL+'/v1/room/select?'+data).then((response)=>{
    if (response.data.code === 2000){
      roomArr.value = response.data.data;
      console.log(roomArr.value);
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}
//自动更新
onMounted(()=>{
  loadRoom();
})

//定义重置搜索方法
const resetSearch = () =>{
  searchRoomForm.value = {};//
  loadRoom();
}
//编辑房间方法
const editRoom = (id)=>{
  roomVisible.value=true;
  roomTitle.value='编辑房间';

  axios.get(BASE_URL+'/v1/room/select?id='+id).then((response)=>{
    if (response.data.code === 2000){
      saveRoomForm.value = response.data.data[0];
      console.log(saveRoomForm.value)
    }
    else {
      ElMessage.error(response.data.msg)
    }
  })

}

const deleteRoom = (roomId)=>{
  if(confirm('您确认要删除当前房间吗?')){
    axios.post(BASE_URL+'/v1/room/delete/'+roomId).then((response)=>{
      if(response.data.code==2000){
        ElMessage.success('删除成功!');
        //删除成功后,重新加载所有房间数据
        loadRoom();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}

//定义数组用来保存房间字典项
const roomTypeArr = ref([]);
onMounted(()=>{
  loadDictOptions(roomTypeArr,'room');
})

const roomTypeFormatter = (row,column,cellValue,index)=>{
  if(!roomTypeArr.value){
    return cellValue;
  }
  for(let item of roomTypeArr.value){
    if(item.value == cellValue){
      cellValue = item.label;
    }
  }
  return cellValue;
}

//查看详情
const particularsVisible = ref(false);
const particularsData = ref({
  roomNumber: '',
  type: '',
  capacity: '',
  status: '',
});

const roomId = ref();
const findAll = (id) => {
  particularsVisible.value = true;
  roomId.value = id;
  axios.get(BASE_URL + '/v1/room/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          particularsData.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}


const updateStatus = (id, status) => {
  axios.put(BASE_URL + '/v1/room/update/status/' + id + '/' + status)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('状态修改成功!')
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}

</script>

<style scoped>
.rotate-icon {
  transform: rotate(90deg);
  transition: transform .3s;
}
</style>